package org.tote.service.user;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tote.dao.DaoFacade;
import org.tote.model.User;

@Service("userDetailsService")
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private DaoFacade daoFacade;

	@Override
	public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException,
			DataAccessException {
		User user = daoFacade.getUserDao().findByLogin(login);
		if (user == null) {
			throw new UsernameNotFoundException("User '" + login + "' not found!");
		}
		//user.setRoles(daoFacade.getRoleDao().getUserRoles(user.getId()));
		Hibernate.initialize(user.getRoles());
		return new CustomUserDetails(user);
	}
}
